<script setup lang="ts">
definePageMeta({
  layout: 'index-page-layout'
})
const startAddr: Ref<string | null> = ref('')
const endAddr: Ref<string | null> = ref('')
const departureTime = ref()

const loading = ref(false);

function getLocation(): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    let location: string = ''
    if (!navigator.geolocation) {
      console.log('不支持定位功能')
      showNotify('不支持定位功能')
      resolve('')
    }
    navigator.geolocation.getCurrentPosition(function (position) {
      let latitude = position.coords.latitude; // 获取纬度
      let longitude = position.coords.longitude; // 获取经度
      location = latitude.toString() + ',' + longitude.toString()
      resolve(location)
    }, function (err) {
      console.log(err)
      showNotify('定位失败')
      reject(err)
    })
  })
}

async function getAddrByLocation(location: string) {
  await $fetch<string>('/reverse_geocoding/v3', {
    baseURL:useRuntimeConfig().public.baseURL,
    method: 'GET',
    params: {
      ak: useRuntimeConfig().public.ak,
      output: 'json',
      coordtype: 'wgs84ll',
      location: location
    },
  }).then(res => {
    let t: GeolocationResponse = JSON.parse(res)
    startAddr.value = t.result.formatted_address
    console.log(t)
  }).catch(err => {
    console.log(err)
  })
}

async function automaticOrientation() {
  showNotify({
    message: "自动获取定位中……",
    type: "primary",
    duration: 3000
  })
  loading.value = true
  let location: string = await getLocation()
  // console.log(location)
  if (location) {
    await getAddrByLocation(location)
    let t: string[] = location.split(',')
    let t1 = t[1] + ',' + t[0];
    localStorage.setItem('from', startAddr.value + '#' + t1)
    loading.value = false
  } else {
    showNotify({
      message: "获取定位失败",
      type: "warning",
      duration: 2000
    })
    console.log('定位失败')
  }
}

onMounted(function (): void {
  barTitleStore().setTitle('乘客端 - 首页')
  let from: string | null = localStorage.getItem('from')
  startAddr.value = from ? from.split('#')[0] : ''

  let to: string | null = localStorage.getItem('to')
  endAddr.value = to ? to.split('#')[0] : ''

  let time: string | null = localStorage.getItem('time')
  departureTime.value = time ? time : ''
})

function saveDate(date: string): boolean {
  localStorage.setItem('time', date)
  // console.log(date)
  return true
}

const quick: Ref<boolean> = ref(false)
const onSubmit = async (values: any) => {
  if (startAddr.value?.trim().length === 0 || endAddr.value?.trim().length === 0) {
    showToast('请选择起点和目的地')
    return
  }
  let start = localStorage.getItem('from')
  let end = localStorage.getItem('to')

  let s_location: string[] = start ? start.split('#')[1].split(',') : ['', '']
  let e_location: string[] = end ? end.split('#')[1].split(',') : ['', '']

  let requestBody: TripDetails = {
    startAddr: startAddr.value ? startAddr.value : '',
    startGeoLat: s_location[1],
    startGeoLng: s_location[0],
    endAddr: endAddr.value ? endAddr.value : '',
    endGeoLat: e_location[1],
    endGeoLng: e_location[0],
    quantity: '1',
    role: roleStore().getRole(),
    status: '0',
    departureTime: values.departureTime,
    quickConfirm: values.quick ? '1' : '0',
  };
  // requestBody.startAddr=startAddr.value?startAddr.value:""
  let res = await cFetch('/stroke/api/publish', {
    auth: true,
    defaultOpts: {
      method: 'POST',
      body: requestBody
    }
  }) as ApiResponse<StrokePO>
  //TODO 发布行程后的业务逻辑 ✓
  if (res.code === 200) {
    showToast('发布成功')
    navigateTo('/stroke')
  }
  // console.log(res.code)
  // console.log('bb', requestBody);
};

</script>

<template>
  <van-image
      :src="ResourceGetter('home.png')"
  />
  <div class="content">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="departureTime"
            name="departureTime"
            label="出发时间"
            type="datetime-local"
            :rules="[
                {required:true,message:'请选择时间'},
                {
                  validator:saveDate,
                  trigger:'onChange'
                }
            ]"
        />
        <van-field name="startAddr" label="出发地">

          <template #input>
            <a href="/map.html?type=f">
              <input v-model="startAddr" readonly placeholder="点击选择" style="border: none;color: black"/>
            </a>
          </template>

          <template #button>
            <van-icon v-if="!loading" name="location-o" @click="automaticOrientation"/>
            <svg v-if="loading" style="position: relative;top:4px;" x="1737121784489" class="icon"
                 viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="18"
                 height="18">
              <path
                  d="M484 64h56c4.42 0 8 3.58 8 8v248c0 4.42-3.58 8-8 8h-56c-4.42 0-8-3.58-8-8V72c0-4.42 3.58-8 8-8z m0 632h56c4.42 0 8 3.58 8 8v248c0 4.42-3.58 8-8 8h-56c-4.42 0-8-3.58-8-8V704c0-4.42 3.58-8 8-8z m324.98-520.58l39.6 39.6c3.12 3.12 3.12 8.19 0 11.31L673.22 401.69c-3.12 3.12-8.19 3.12-11.31 0l-39.6-39.6c-3.12-3.12-3.12-8.19 0-11.31l175.36-175.36c3.13-3.13 8.19-3.13 11.31 0zM362.09 622.31l39.6 39.6c3.12 3.12 3.12 8.19 0 11.31L226.33 848.58c-3.12 3.12-8.19 3.12-11.31 0l-39.6-39.6c-3.12-3.12-3.12-8.19 0-11.31l175.36-175.36a7.985 7.985 0 0 1 11.31 0zM960 484v56c0 4.42-3.58 8-8 8H704c-4.42 0-8-3.58-8-8v-56c0-4.42 3.58-8 8-8h248c4.42 0 8 3.58 8 8z m-632 0v56c0 4.42-3.58 8-8 8H72c-4.42 0-8-3.58-8-8v-56c0-4.42 3.58-8 8-8h248c4.42 0 8 3.58 8 8z m520.58 324.98l-39.6 39.6c-3.12 3.12-8.19 3.12-11.31 0L622.31 673.22c-3.12-3.12-3.12-8.19 0-11.31l39.6-39.6c3.12-3.12 8.19-3.12 11.31 0l175.36 175.36c3.13 3.13 3.13 8.19 0 11.31zM401.69 362.09l-39.6 39.6c-3.12 3.12-8.19 3.12-11.31 0L175.42 226.33c-3.12-3.12-3.12-8.19 0-11.31l39.6-39.6c3.12-3.12 8.19-3.12 11.31 0l175.36 175.36a7.985 7.985 0 0 1 0 11.31z"
                  fill="#bfbfbf"></path>
            </svg>
          </template>
        </van-field>

        <van-field name="endAddr" label="目的地">
          <template #input>
            <a href="/map.html?type=t">
              <input v-model="endAddr" readonly placeholder="点击选择" style="border: none;color: black;"/>
            </a>
          </template>
        </van-field>

        <van-field name="quick" label="快速确认">
          <template #input>
            关&nbsp;&nbsp;<van-switch v-model="quick"/>&nbsp;&nbsp;开
          </template>
        </van-field>

      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          发布行程
        </van-button>
      </div>
    </van-form>
  </div>

</template>

<style scoped>
.content {
  background-color: white;
  border-radius: 15px;
  position: absolute;
  top: 47%;
  opacity: 0.92;
}

</style>